﻿import math


def read_data(way, split_char=None):
    line_array, result_array = [], []
    try:
        for file_line in open(way, encoding="utf-8"):
            if split_char is not None:
                line_array = file_line.split(split_char)
            else:
                line_array = file_line
            result_array.append(line_array)
        return result_array
    except:
        raise ValueError("Wrong File Path:" + way)


def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        pass


def take_score(path_name):
    scores = "拖堂时间如下（s）：\n"
    the_sum = 0
    times = 0
    preparingScore = ""
    try:
        for file_line in open("bin/data/subject_time/" + path_name + ".dat"):
            preparingScore = preparingScore + file_line
            times += 1
            the_sum += int(file_line)
        if times != 0:
            avg = the_sum / times
        else:
            avg = 0
        avg = format(avg, ".2f")
        avg = float(avg)
        scores = scores + "平均成绩：" + str(avg) + "s\n"
        sqareAdd = 0
        for file_line in open("bin/data/subject_time/" + path_name + ".dat"):
            sqareAdd += int((int(file_line) - avg) ** 2)
        if times != 0:
            _sqare = sqareAdd / times
        else:
            _sqare = 0
        _sqare = format(_sqare, "-2f")
        _sqare = float(_sqare)
        scores = scores + "方差：" + str(_sqare) + "\n"
        scores = scores + preparingScore
        return scores, avg
    except:
        raise ValueError("Wrong File Path while taking score")

def take_avg_rank():
    subject_name = ["chi", "math", "eng", "phy", "chem", "bio", "his", "geo", "pol"]
    subject_translate = ["语文", "数学", "英语", "物理", "化学", "生物", "历史", "地理", "政治"]
    subject_score = []
    for each_subject in subject_name:
        the_sum = 0
        times = 0
        try:
            for file_line in open("bin/data/subject_time/" + each_subject + ".dat"):
                the_sum += int(file_line)
                times += 1
            if times != 0:
                avg = the_sum / times
            else:
                avg = 0
            avg = format(avg, ".2f")
            avg = float(avg)
            subject_score.append(float(avg))
        except:
            raise ValueError("Wrong File Path while ranking")
    now_ranking = 1
    result_string = ""
    preparing_translate = subject_translate
    preparing_score = subject_score
    while len(preparing_translate) >= 1:
        index = 0
        while index + 1 < len(preparing_translate):
            if preparing_score[index] > preparing_score[index + 1]:
                c = preparing_score[index]
                preparing_score[index] = preparing_score[index + 1]
                preparing_score[index + 1] = c
                c = preparing_translate[index]
                preparing_translate[index] = preparing_translate[index + 1]
                preparing_translate[index + 1] = c
            index += 1
        result_string = result_string + "第" + str(now_ranking) + "名：" + \
            preparing_translate[len(preparing_translate) - 1] + "（" + \
        str(preparing_score[len(preparing_score) - 1]) + \
            "s）\n"
        preparing_translate.remove(preparing_translate[len(preparing_translate) - 1])
        preparing_score.remove(preparing_score[len(preparing_score) - 1])
        now_ranking += 1
    return result_string

def take_squ_rank():
    subject_name = ["chi", "math", "eng", "phy", "chem", "bio", "his", "geo", "pol"]
    subject_translate = ["语文", "数学", "英语", "物理", "化学", "生物", "历史", "地理", "政治"]
    subject_score = []
    for each_subject in subject_name:
        the_sum = 0
        times = 0
        try:
            for file_line in open("bin/data/subject_time/" + each_subject + ".dat"):
                the_sum += int(file_line)
                times += 1
            if times != 0:
                avg = the_sum / times
            else:
                avg = 0
            sqareAdd = 0
            for file_line in open("bin/data/subject_time/" + each_subject + ".dat"):
                sqareAdd += int((int(file_line) - avg) ** 2)
            if times != 0:
                _sqare = sqareAdd / times
            else:
                _sqare = 0
            now_sqare = float(_sqare)
            now_sqare = format(now_sqare, ".2f")
            subject_score.append(float(now_sqare))
        except:
            raise ValueError("Wrong File Path while ranking")
    now_ranking = 1
    result_string = ""
    preparing_translate = subject_translate
    preparing_score = subject_score
    while len(preparing_translate) >= 1:
        index = 0
        while index + 1 < len(preparing_translate):
            if preparing_score[index] < preparing_score[index + 1]:
                c = preparing_score[index]
                preparing_score[index] = preparing_score[index + 1]
                preparing_score[index + 1] = c
                c = preparing_translate[index]
                preparing_translate[index] = preparing_translate[index + 1]
                preparing_translate[index + 1] = c
            index += 1
        result_string = result_string + "第" + str(now_ranking) + "名：" + \
            preparing_translate[len(preparing_translate) - 1] + "（" + \
        str(preparing_score[len(preparing_score) - 1]) + \
            "）\n"
        preparing_translate.remove(preparing_translate[len(preparing_translate) - 1])
        preparing_score.remove(preparing_score[len(preparing_score) - 1])
        now_ranking += 1
    return result_string

def add_score(path_name, new_score):
    readingFile = open("bin/data/subject_time/" + path_name + ".dat", 'r')
    scores = readingFile.read()
    readingFile.close()
    try:
        readingFile2 = open("bin/data/subject_time/" + path_name + ".dat", 'w')
        readingFile2.write(str(new_score) + "\n")
        readingFile2.write(scores)
        readingFile2.close()
    except:
        readingFile2.close()
